<?php
namespace app\admin\controller;
use cmf\controller\AdminBaseController;
use think\Db;
use think\Loader;
use think\Request;

class OrderController extends AdminBaseController
{
	public function index()
	{
		$content = hook_one('admin_order_index_view');
		if (!empty($content)) {
			return $content;
		}

		$where = ['id' => ['neq', 0]];
		/**搜索条件**/
		$useremail = $this->request->param('useremail');
		if ($useremail) {
			$where['useremail'] = ['like', "%$useremail%"];
		}

		$orderList = Db::name('order')
			->where($where)
			->order("id DESC")
			->paginate(80);

		$orderList->appends(['useremail' => $useremail]);
		// 获取分页显示
		$page = $orderList->render();

		$this->assign("page", $page);
		$this->assign("orderList", $orderList);
		return $this->fetch();
	}

	public function add()
	{
		return $this->fetch();
	}

	public function addPost()
	{
		if ($this->request->isPost()) {
			if (!empty($_POST['useremail'])) {
				$_POST["create_time"] = date("Y-m-d H:i:s");
				$_POST["update_time"] = date("Y-m-d H:i:s");
				
				$result	= DB::name('order')->insertGetId($_POST);
				if ($result !== false) {
						$this->success("添加成功！", url("order/index"));
					} else {
						$this->error("添加失败！");
					}
			} else {
				$this->error("买家邮箱能为空！");
			}
		}
	}

	public function edit()
	{
		$content = hook_one('admin_order_edit_view');

		if (!empty($content)) {
			return $content;
		}

		$id      = $this->request->param('id', 0, 'intval');
		$order = DB::name('order')->where(["id" => $id])->find();
		$this->assign($order);
		return $this->fetch();
	}

	public function editPost()
	{
		if ($this->request->isPost()) {
			if (!empty($_POST['id'])) {
				$_POST["update_time"] = date("Y-m-d H:i:s");
				$result = DB::name('order')->update($_POST);
				if ($result !== false) {
						$this->success("添加成功！", url("order/index"));
					} else {
						$this->error("添加失败！");
					}
			} else {
				$this->error("ID不能为空！");
			}
		}
	}

	public function delete()
	{
		$id = $this->request->param('id', 0, 'intval');

		if (Db::name('order')->delete($id) !== false) {
			$this->success("删除成功！");
		} else {
			$this->error("删除失败！");
		}
	}

	
	public function importview(){
		return $this->fetch();
	}

	//数据导入
	public function importdata(){
		//Excel导入 添加用户
		if($this->request->isPost()){
	        $excel_name = $this->request->param('excel_name');
	        $excel_url = $this->request->param('excel_url');
	        if(!empty($excel_name) && !empty($excel_url)){
	            Loader::import('PHPExcel.Classes.PHPExcel');
	            Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');
	            Loader::import('PHPExcel.Classes.PHPExcel.Reader.Excel5');
	            $filename = ROOT_PATH.'public/upload/'.$excel_url;  //文件路径
	            $extension = cmf_get_file_extension($excel_url);    //文件扩展名
	            if($extension == 'xlsx'){
	                $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
	                $objPHPExcel = $objReader->load($filename, $encode = 'utf-8');  //加载文件内容,编码utf-8
	            }else if($extension == 'xls'){
	                $objReader =\PHPExcel_IOFactory::createReader('Excel5');
	                $objPHPExcel = $objReader->load($filename, $encode = 'utf-8');  //加载文件内容,编码utf-8
	            }else{
	                $this->error('请上传Excel格式的文件！','');
	            }
	            $excel_array=$objPHPExcel->getsheet(0)->toArray();   //转换为数组格式
	            array_shift($excel_array);  //删除第一个数组(标题);
	            $data = [];
	            
	            //获取已有的站点邮箱进行匹配
				$webmailList = Db::name('webmail')->field('websitename,emailname')->select();
				$webmailArr = $webmailArrKey = array();
				foreach ($webmailList as $k => $v) {
					$key = explode('.', $v['websitename']);
					$key = $key[1];
					$webmailArrKey[] = $key;
					$webmailArr[$key] = $v['emailname'];
				}

	            foreach($excel_array as $k=>$v) {
	            	$webSiteArr = explode('-', $v[0]);
			$websiteName = '';
	            	if(count($webSiteArr) == 4){
	            		$websiteName = $webSiteArr[0];
	            	}elseif(count($webSiteArr) == 5){
	            		$websiteName = $webSiteArr[0].'-'.$webSiteArr[1];
	            	}elseif(count($webSiteArr) == 1){
	            		$websiteName = $webSiteArr[0];
	            	}
	            	$websiteName = str_replace('爆品', '', $websiteName);
	            	if($websiteName && in_array($websiteName, $webmailArrKey)){
	            		$website = $webmailArr[$websiteName];
	            	}else{
	            		//$website = '未找到';
				$website = 'Chargeiuwq7305@gmail.com';
	            	}
	                $data[$k]['logwebsite'] 	= empty($v[0])? '' : $v[0];
	                $data[$k]['useremail'] 		= empty($v[1])? '496042513@qq.com' : $v[1];
	                $data[$k]['username'] 		= empty($v[2])? '' : $v[2];
	                $data[$k]['orderid'] 		= empty($v[3])? '' : $v[3];
	                $data[$k]['logpakename'] 	= empty($v[4])? '' : $v[4];
	                $data[$k]['logsendway'] 	= empty($v[5])? '' : $v[5];
			$data[$k]['logsendwayname'] 	= empty($v[6])? '' : $v[6];
	                $data[$k]['websitemail'] 	= empty($website)? '' : $website;
			$data[$k]["eximport_time"] = date("Y-m-d");
	                $data[$k]["create_time"] = date("Y-m-d H:i:s");
					$data[$k]["update_time"] = date("Y-m-d H:i:s");
	            }
	            if($data){
	            	DB::name('order')->insertAll($data);
	                $this->success('导入数据成功！',url("order/index"));
	            } else {
	                $this->error('导入数据失败!','');
	            }
	        }else{
	            $this->error('文件导入失败!','');
	        }
	    }
	}
	
	//数据分析
	public function datashow()
	{
		$content = hook_one('admin_order_datashow_view');
		if (!empty($content)) {
			return $content;
		}

		$where = ['id' => ['neq', 0]];
		/**搜索条件**/
		$showdate = $this->request->param('showdate');
		if (!$showdate) {
			$showdate = date("Y-m-d");
		}
		//$where  = " where eximport_time = '$showdate'";
		// $where = '';
		$orderList = Db::name('order')->query("select count(*) as allnum , logwebsite  from cmf_order where eximport_time = '$showdate' group by logwebsite order by allnum desc ;");
		$allData['data_num']  = $allData['data_wait'] =$allData['data_nodetail'] =$allData['data_noemail'] =$allData['data_nopwd'] =$allData['data_pwd_worng'] = $allData['data_sucess'] = 0;
		foreach ($orderList as $k => $v) {
			$logwebsite = $v['logwebsite'];
			$listMore = Db::name('order')->query("select count(*) as sendnum, sendstatus from cmf_order where eximport_time = '$showdate' and logwebsite = '$logwebsite' group by sendstatus;");
			$lastId = Db::name('order')->query("select id from cmf_order where eximport_time = '$showdate' and logwebsite = '$logwebsite' and sendstatus = 200 order by id desc limit 1");
			$orderList[$k]['lastId'] = empty($lastId)? 0 : $lastId[0]['id'];
			$orderList[$k]['data_wait'] = $orderList[$k]['data_nodetail'] = $orderList[$k]['data_noemail'] = $orderList[$k]['data_nopwd'] = $orderList[$k]['data_pwd_worng'] = $orderList[$k]['data_sucess'] = 0;
			foreach ($listMore as $kk => $vv) {
				if($vv['sendstatus']	== 100){$orderList[$k]['data_wait'] 	=	$vv['sendnum']; continue;}
				if($vv['sendstatus'] 	== 101){$orderList[$k]['data_nodetail'] =	$vv['sendnum']; continue;}
				if($vv['sendstatus'] 	== 102){$orderList[$k]['data_noemail'] 	=	$vv['sendnum']; continue;}
				if($vv['sendstatus'] 	== 103){$orderList[$k]['data_nopwd'] 	=	$vv['sendnum']; continue;}
				if($vv['sendstatus']	== 104){$orderList[$k]['data_pwd_worng']=	$vv['sendnum']; continue;}
				if($vv['sendstatus'] 	== 200){$orderList[$k]['data_sucess'] 	=	$vv['sendnum']; continue;}
			}	
			$orderList[$k]['logwebsite'] 	= empty($logwebsite)? '无人认领' : $v['logwebsite'];
			$allData['data_num'] 		+= $v['allnum'];
			$allData['data_wait'] 		+= $orderList[$k]['data_wait'];
			$allData['data_nodetail'] 	+= $orderList[$k]['data_nodetail'];
			$allData['data_noemail'] 	+= $orderList[$k]['data_noemail'];
			$allData['data_nopwd'] 		+= $orderList[$k]['data_nopwd'];
			$allData['data_pwd_worng'] 	+= $orderList[$k]['data_pwd_worng'];
			$allData['data_sucess'] 	+= $orderList[$k]['data_sucess'];
		}
		$this->assign("orderList", $orderList);
		$this->assign("showdate", $showdate);
		$this->assign("allData", $allData);
		return $this->fetch();
	}
}
